@echo off
:: 设置 CMD 编码为 UTF-8 以支持中文
chcp 65001 >nul
echo Starting SurveyApp packaging...

:: 确保 PyInstaller 已安装
pip install pyinstaller
if %ERRORLEVEL% NEQ 0 (
    echo Error: Failed to install PyInstaller. Please check pip and network connection.
    pause
    exit /b %ERRORLEVEL%
)

:: 设置输出目录和文件名
set OUTPUT_DIR=dist
set EXE_NAME=SurveyApp
set SPEC_FILE=%EXE_NAME%.spec
set BUILD_DIR=build

:: 清除之前的打包文件
echo Clearing previous build files...
if exist "%OUTPUT_DIR%" (
    rmdir /s /q "%OUTPUT_DIR%"
    echo Deleted dist directory
)
if exist "%BUILD_DIR%" (
    rmdir /s /q "%BUILD_DIR%"
    echo Deleted build directory
)
if exist "%SPEC_FILE%" (
    del /q "%SPEC_FILE%"
    echo Deleted %SPEC_FILE%
)

:: 运行 PyInstaller 打包
echo Running PyInstaller...
pyinstaller ^
    --noconfirm ^
    --onefile ^
    --windowed ^
    --name %EXE_NAME% ^
    --add-data "gui_settings.json;." ^
    --add-data "surveys;surveys" ^
    --icon NONE ^
    --hidden-import tkinter ^
    --hidden-import selenium ^
    --hidden-import requests ^
    --hidden-import retrying ^
    --clean ^
    gui.py

:: 检查 PyInstaller 是否成功
if %ERRORLEVEL% NEQ 0 (
    echo Error: PyInstaller packaging failed. Please check the error messages.
    pause
    exit /b %ERRORLEVEL%
)

echo Packaging complete! Executable located at: %OUTPUT_DIR%\%EXE_NAME%.exe
echo Note: Check dist/gui_settings.json after running.
pause